<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 * source: http://www.ipinfodb.com/ip_location_api_json.php
 * author: longuyvinh (July/04 2014)
 */

class iplocation {

    public $ipAddress = '';
    public $apiKey = '';

    public function init() {
        include('/class/ip2locationlite.class.php');
        // Set required classes for import
        // example set static ip
        //$this->ipAddress = '192.95.59.247';
        $this->ipAddress = (ip() == '127.0.0.1' || ip() == '::1') ? '192.95.59.247' : ip();
        //echo $this->ipAddress;
        //die('vinh bug');
        //set api on ipinfodb.com
        $this->apiKey = '238e3836580389fb4b6475e49fd91b18342155283eeb6d56ba4b4653ac550caf';
    }

    //function custom static IP
    public function getInfoTest($ip) {
        $ipLite = new ip2location_lite;
        $ipLite->setKey($this->apiKey);

        //Get errors and locations
        $locations = $ipLite->getCity($ip);
        $errors = $ipLite->getError();

        if (isset($errors)) {
            return $locations;
        } else {
            return $errors;
        }
    }

    //function get dynamic IP
    public function getInfo() {
        //check ip exist on database
        $ipCheck = Ipaddress::model()->findByPk($this->ipAddress);
        if (isset($ipCheck)) {
            $result = json_decode($ipCheck->data);
            return $result;
        } else {
            //Load the class
            $ipLite = new ip2location_lite;
            $ipLite->setKey($this->apiKey);

            //Get errors and locations
            $locations = $ipLite->getCity($this->ipAddress);
            $errors = $ipLite->getError();

            if (isset($errors)) {
                $ip = new Ipaddress();
                $ip->ipAddress = $this->ipAddress;
                $ip->data = json_encode($locations);
                $ip->save();
                return $locations;
            } else {
                return $errors;
            }
        }
    }

}
